﻿using System;
using System.Windows.Controls;
using System.Windows.Media;
using TicTacToe.Core;

namespace _3DTicTacToe.UI.Components
{
    internal partial class PlayerPropertyControl : UserControl
    {
        private static readonly Brush InvalidColorBrush = Brushes.OrangeRed;
        private static readonly Brush ValidColorBrush = Brushes.White;
        private static readonly BrushList BList = new BrushList();

        public delegate void BoolDlg(bool valid);
        public event BoolDlg PlayerPropsChanged; 

        public bool IsPlayerChosen { get; private set; }

        public Player Player { get { return new Player(nameTBox.Text, (Color)ColorConverter.ConvertFromString(colorCBox.SelectedItem as string)); } }
        public string PlayerName { get { return nameTBox.Text; } }

        public int SelectedColorIndex
        {
            get
            {
                return colorCBox.SelectedIndex;
            }
            set
            {
                colorCBox.SelectedIndex = value;
            }
        }

        public PlayerPropertyControl()
        {
            InitializeComponent();

            nameTBox.Background = InvalidColorBrush;
            colorCBox.DataContext = BList;

            colorCBox.SelectedIndex = 0;

            nameTBox.TextChanged += ValidateName;

            var rng = new Random();
            colorCBox.SelectedIndex = rng.Next(0, BList.Count+1);
        }

        void ValidateName(object sender, TextChangedEventArgs e)
        {
            if (Player.IsValidName(nameTBox.Text))
            {
                IsPlayerChosen = true;
                nameTBox.Background = ValidColorBrush;
            }
            else
            {
                IsPlayerChosen = false;
                nameTBox.Background = InvalidColorBrush;
            }

            if (PlayerPropsChanged != null) PlayerPropsChanged(IsPlayerChosen);
        }
    }
}
